package com.bedrock.project.inside.api.v1;

import java.text.ParseException;
import java.util.List;

import com.bedrock.common.utils.IdWord;
import com.bedrock.common.utils.file.FileUploadUtils;
import com.bedrock.framework.config.BedrockConfig;
import com.bedrock.framework.config.ServerConfig;
import com.bedrock.framework.security.LoginUser;
import com.bedrock.framework.security.service.TokenService;
import com.bedrock.project.common.CommonController;
import com.bedrock.project.enums.ResCode;
import com.bedrock.project.inside.entity.Interviewer;
import com.bedrock.project.inside.service.IInterviewerService;
import com.bedrock.project.inside.vo.request.InterviewerFlowVo;
import com.bedrock.project.system.domain.SysRole;
import com.sun.jna.platform.win32.WinDef;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.bedrock.framework.aspectj.lang.annotation.Log;
import com.bedrock.framework.aspectj.lang.enums.BusinessType;
import com.bedrock.project.inside.entity.RecruitEntity;
import com.bedrock.project.inside.service.IRecruitService;
import com.bedrock.framework.web.controller.BaseController;
import com.bedrock.framework.web.domain.AjaxResult;
import com.bedrock.common.utils.poi.ExcelUtil;
import com.bedrock.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * 招聘Controller
 * 
 * @author bedrock
 * @date 2020-04-07
 */
@RestController
@RequestMapping("/inside/recruit")
public class RecruitController extends BaseController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private IRecruitService recruitService;

    private static final Logger log = LoggerFactory.getLogger(RecruitController.class);

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询招聘列表 @PreAuthorize("@ss.hasPermi('system:recruit:list')")
     */
    @ApiOperation("招聘列表 -- wengus")
    @ApiImplicitParams({
            @ApiImplicitParam(name="joberName",value="求职者名称",dataType="string", required = false ,paramType = "query",example="xingguo"),
            @ApiImplicitParam(name="jobberStatic",value="求职者状态",dataType="Long",  required = false ,paramType = "query",example="1"),
            @ApiImplicitParam(name="flowId",value="求职者状态",dataType="Long",  required = false ,paramType = "query",example="1")
    })

    @GetMapping("/list")
    public TableDataInfo<List<RecruitEntity>> list(@RequestParam(required = false) String joberName,
                              @RequestParam(required = false) Long jobberStatic,
                              @RequestParam(required = false) Long flowId,
                              HttpServletRequest request)
    {

        RecruitEntity recruitEntity = new RecruitEntity();
        if(joberName!=null){
            recruitEntity.setJoberName(joberName);
        }
        if(jobberStatic!=null){
            recruitEntity.setJobberStatic(jobberStatic);
        }
        if(flowId!=null){
            recruitEntity.setFlowId(flowId);
        }
        startPage();
        List<RecruitEntity> list = recruitService.selectRecruitEntityList(recruitEntity);
        return getDataTable(list);
    }


    /**
     * 查询招聘列表 @PreAuthorize("@ss.hasPermi('system:recruit:list')")
     */
    @ApiOperation("招聘待办列表 -- wengus")
    @ApiImplicitParams({
    })
    @GetMapping("/listwait")
    public TableDataInfo<List<RecruitEntity>> listWait(HttpServletRequest request)
    {

        RecruitEntity recruitEntity = new RecruitEntity();
        LoginUser loginUser = tokenService.getLoginUser(request);
        List<SysRole> listRole = loginUser.getUser().getRoles();
        Long num = listRole.stream().filter(x->x.getRoleName().equals("HR")).count();

        if(num>0){
            // 是HR登录待办页面
            recruitEntity.setIsHR("yes");
        }else{
            // 是面试官登录待办页面
            recruitEntity.setIsHR("no");
        }

        startPage();
        List<RecruitEntity> list = recruitService.selectRecruitEntityList(recruitEntity);
        return getDataTable(list);
    }


    //@PreAuthorize("@ss.hasPermi('system:recruit:export')")
    /**
     * 导出招聘列表
     */
    @ApiOperation("招聘列表导出 -- wengus")
    @ApiImplicitParams({
            @ApiImplicitParam(name="joberName",value="求职者名称",dataType="string", required = false ,paramType = "query",example="xingguo"),
            @ApiImplicitParam(name="jobberStatic",value="求职者状态",dataType="Long",  required = false ,paramType = "query",example="1")})

    @Log(title = "招聘列表导出", businessType = BusinessType.EXPORT)
    @GetMapping("/export")

    public AjaxResult export(@RequestParam(required = false) String joberName,
                             @RequestParam(required = false) Long jobberStatic)
    {
        RecruitEntity recruitEntity = new RecruitEntity();
        if(joberName!=null){
            recruitEntity.setJoberName(joberName);
        }
        if(jobberStatic!=null){
            recruitEntity.setJobberStatic(jobberStatic);
        }
        List<RecruitEntity> list = recruitService.selectRecruitEntityList(recruitEntity);
        ExcelUtil<RecruitEntity> util = new ExcelUtil<RecruitEntity>(RecruitEntity.class);
        return util.exportExcel(list, "recruit");
    }

    //@PreAuthorize("@ss.hasPermi('system:recruit:query')")
    /**
     * 获取招聘详细信息
     */
    @ApiOperation("招聘详情 -- wengus")
    @ApiImplicitParams({
            @ApiImplicitParam(name="id",value="id编号",dataType="Long", required = false ,paramType = "path",example="1"),
            })
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(recruitService.selectRecruitEntityById(id));
    }

    //@PreAuthorize("@ss.hasPermi('system:recruit:add')")
    /**
     * 新增招聘
     */
    @ApiOperation("招聘新增 -- wengus")
    @Log(title = "招聘新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RecruitEntity recruitEntity,HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if(recruitEntity.getId()==null){
            recruitEntity.setId(IdWord.getId());
        }
        int result = 0;
        try{
            recruitEntity.setJobberStatic(1L);
            recruitEntity.setRecUserId(loginUser.getUser().getUserId());
            recruitEntity.setCreateBy(String.valueOf(loginUser.getUser().getUserId()));
            result =  recruitService.insertRecruitEntity(recruitEntity);
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return toAjax(result);
    }

    //@PreAuthorize("@ss.hasPermi('system:recruit:edit')")
    /**
     * 修改招聘
     */
    @ApiOperation("招聘修改 -- wengus")
    @Log(title = "招聘修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RecruitEntity recruitEntity)
    {

        // 流程判断
       // 0 未开始 1 待筛选 2 未通过 3 待预约 4 待面试 5 面试未通过 6 面试已通过 7 待定(都有可能性)

        return toAjax(recruitService.updateRecruitEntity(recruitEntity));
    }

    //    @PreAuthorize("@ss.hasPermi('system:recruit:remove')")
    /**
     * 删除招聘
     */
    @ApiOperation("招聘删除 -- wengus")
    @ApiImplicitParams({
            @ApiImplicitParam(name="ids",value="id编号list",dataType="Long", required = false ,paramType = "path",example="1"),
    })
    @Log(title = "招聘删除", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {

        return toAjax(recruitService.deleteRecruitEntityByIds(ids));
    }

    /**
     *
     * 面试官分配功能
     */
    @ApiOperation("面试官分配 -- wengus")
    @ApiImplicitParams({
            @ApiImplicitParam(name="recuritId",value="求职表Id",dataType="Long", required = true,paramType = "query",example="12"),
            @ApiImplicitParam(name="technologyId",value="技术类型id",dataType="Long", required = true,paramType = "query",example="12"),
            @ApiImplicitParam(name="joberName",value="求职者姓名",dataType="string", required = true,paramType = "query",example="12"),
           // @ApiImplicitParam(name="doUserId",value="处理人(面试官表Id)",dataType="Long", required = true,paramType = "query",example="12")

    })
    @Log(title = "面试官分配功能", businessType = BusinessType.INSERT)
    @GetMapping("/viewerset")
    public AjaxResult viewerset(@RequestParam("recuritId") Long recuritId,
                                @RequestParam("technologyId") Integer technologyId,
                                @RequestParam("joberName") String joberName,
                                HttpServletRequest request){

        LoginUser loginUser = tokenService.getLoginUser(request);
        Interviewer interviewer = new Interviewer();

        // 求职者表ID
        interviewer.setRecuritId(recuritId);
        interviewer.setTechnologyId(technologyId);
        interviewer.setCreateBy(String.valueOf(loginUser.getUser().getUserId()));
        // 待筛选
        interviewer.setJobberStatic(1);
        // 求职者名称
        interviewer.setJoberName(joberName);
        // 处理人（面试官）
       // interviewer.setDoUserId(doUserId);

        String result = "";
        try{
            result = recruitService.viewerset(interviewer);
        }catch (Exception ex){
            ex.printStackTrace();
            return  new AjaxResult(ResCode.$4001.getCode(),ex.getMessage()+":"+result);
        }

        return  new AjaxResult(ResCode.$200.getCode(),result);
    }


    /**
     *
     * 面试流转
     */
    @ApiOperation("面试流转 -- wengus")
    @Log(title = "面试流转", businessType = BusinessType.INSERT)
    @PostMapping("/flowto")
    public AjaxResult viewerFlowTo(@RequestBody InterviewerFlowVo flowVo, HttpServletRequest request){

        String result = "";
        try{
            if(flowVo.getMakeTime() !=null ) {
                new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(flowVo.getMakeTime());
            }
            result = recruitService.flowTo(flowVo);
            return  new AjaxResult(ResCode.$200.getCode(),result);
        }catch (ParseException ex){
            return  new AjaxResult(ResCode.$4089.getCode(),ResCode.$4089.getInfo());
        }catch (Exception ex){
            ex.printStackTrace();
            return  new AjaxResult(ResCode.$4001.getCode(),result);
        }

    }


    /**
     * 简历上传，每次上传都需要将求职者的简历更新为最新的文件
     */
    /**
     *
     * @param file
     * @param recruitId
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation("文件上传 -- wengus")
    @ApiImplicitParams({
            @ApiImplicitParam(name="file",value="文件",dataType="file", required = true,paramType = "object",example="12")
    })
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file,
                                 @RequestParam (name = "recruitId",required = false) String recruitId,
                                 HttpServletRequest request) throws Exception {

        try
        {
            LoginUser loginUser = tokenService.getLoginUser(request);
            // 上传文件路径
            String filePath = BedrockConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);

             String url = serverConfig.getUrl() + fileName;

            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            // 将url更新到数据库中 ， 如果  recruitId 为空表示新增，不为空表示修改
            if(recruitId!=null){
                Long id = Long.parseLong(recruitId);
                recruitService.updateVitaeUrl(url,id,loginUser.getUser().getUserId());
            }
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

}
